import { PlusOutlined, ReloadOutlined } from "@ant-design/icons";
import type { ProColumns } from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import { Badge, Button, Drawer, Space, Tag, Typography, message } from "antd";

import React, { useRef, useState } from "react";

import "./index.less";

const { Title } = Typography;

interface TableItem {
  id: number;
  name: string;
  status: "online" | "offline" | "error";
  type: string;
  createdAt: string;
  progress: number;
}

const mockFetch = async (params: {
  current?: number;
  pageSize?: number;
  keyword?: string;
  status?: string;
}): Promise<{ data: TableItem[]; total: number; success: boolean }> => {
  const { current = 1, pageSize = 10, keyword = "", status } = params;
  const base = Array.from({ length: 57 }).map((_, i) => ({
    id: i + 1,
    name: `服务-${i + 1}`,
    status: (i % 3 === 0
      ? "online"
      : i % 3 === 1
        ? "offline"
        : "error") as TableItem["status"],
    type: ["Web", "DB", "Job"][i % 3],
    createdAt: `2024-11-${(i % 28) + 1}`,
    progress: (i * 7) % 100,
  }));
  const filtered = base.filter(
    (it) => it.name.includes(keyword) && (!status || it.status === status),
  );
  const start = (current - 1) * pageSize;
  const end = start + pageSize;
  return new Promise((resolve) =>
    setTimeout(
      () =>
        resolve({
          data: filtered.slice(start, end),
          total: filtered.length,
          success: true,
        }),
      400,
    ),
  );
};

const Page43: React.FC = () => {
  const actionRef = useRef<any>();
  const [detail, setDetail] = useState<TableItem | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const columns: ProColumns<TableItem>[] = [
    {
      title: "编号",
      dataIndex: "id",
      width: 80,
      search: false,
    },
    {
      title: "名称",
      dataIndex: "name",
      copyable: true,
    },
    {
      title: "类型",
      dataIndex: "type",
      valueType: "select",
      valueEnum: {
        Web: { text: "Web" },
        DB: { text: "DB" },
        Job: { text: "Job" },
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      valueType: "select",
      valueEnum: {
        online: { text: "在线", status: "Success" },
        offline: { text: "离线", status: "Default" },
        error: { text: "异常", status: "Error" },
      },
      render: (_, record) => (
        <Space>
          <Badge
            status={
              record.status === "online"
                ? "success"
                : record.status === "offline"
                  ? "default"
                  : "error"
            }
          />
          <span>
            {record.status === "online"
              ? "在线"
              : record.status === "offline"
                ? "离线"
                : "异常"}
          </span>
        </Space>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      valueType: "date",
    },
    {
      title: "进度",
      dataIndex: "progress",
      valueType: "progress",
      search: false,
    },
    {
      title: "操作",
      valueType: "option",
      width: 160,
      render: (_, record) => [
        <a key="view" onClick={() => setDetail(record)}>
          查看
        </a>,
        <a key="edit">编辑</a>,
        <a key="del" onClick={() => message.success("已删除")}>
          删除
        </a>,
      ],
    },
  ];

  return (
    <div className="page43-page">
      <Title level={2} className="page-title">
        高级表格与批量操作
      </Title>
      <ProTable<TableItem>
        rowKey="id"
        actionRef={actionRef}
        columns={columns}
        request={async (params) => mockFetch(params as any)}
        pagination={{ showSizeChanger: true }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        toolbar={{
          title: selectedRowKeys.length ? (
            <Tag color="blue">已选 {selectedRowKeys.length} 项</Tag>
          ) : undefined,
          actions: [
            <Button key="add" type="primary" icon={<PlusOutlined />}>
              新建
            </Button>,
            <Button
              key="reload"
              icon={<ReloadOutlined />}
              onClick={() => actionRef.current?.reload()}
            />,
          ],
        }}
        search={{ labelWidth: 80 }}
      />

      <Drawer
        title="详情"
        open={!!detail}
        onClose={() => setDetail(null)}
        width={420}
      >
        {detail && (
          <div>
            <p>名称：{detail.name}</p>
            <p>类型：{detail.type}</p>
            <p>状态：{detail.status}</p>
            <p>创建时间：{detail.createdAt}</p>
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default Page43;
